package com.reggie.common;

import cn.hutool.core.util.StrUtil;
import com.reggie.Exception.CustomAddressException;
import com.reggie.Exception.CustomCategoryException;
import com.reggie.Exception.CustomOrderException;
import com.reggie.Exception.CustomSetmealException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 约束异常处理
     *
     * @return 异常信息
     */
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> constraintsExceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());
        if (StrUtil.contains(exception.getMessage(), "Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + "已存在！";
            return R.error(msg);
        }
        return R.error("操作失败" + exception.getMessage());
    }

    /**
     * 分类管理业务异常处理
     *
     * @param exception 捕获异常
     * @return 异常信息
     */
    @ExceptionHandler({CustomCategoryException.class})
    public R<String> categoryExceptionHandler(CustomCategoryException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

    /**
     * 套餐管理业务异常处理
     *
     * @param exception 捕获异常
     * @return 异常信息
     */
    @ExceptionHandler({CustomSetmealException.class})
    public R<String> setmealExceptionHandler(CustomSetmealException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

    /**
     * 订单业务异常处理
     *
     * @param exception 捕获异常
     * @return 异常信息
     */
    @ExceptionHandler({CustomOrderException.class})
    public R<String> orderExceptionHandler(CustomOrderException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

    /**
     * 用户地址异常处理
     *
     * @param exception 捕获异常
     * @return 异常信息
     */
    @ExceptionHandler({CustomAddressException.class})
    public R<String> addressExceptionHandler(CustomAddressException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
